package com.share.hope.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.hope.entity.CommentInfo;
import com.share.hope.entity.UserInfo;
import com.share.hope.entity.result.R;
import com.share.hope.mapper.CommentMapper;
import com.share.hope.service.CommentInfoService;
import com.share.hope.service.UserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CommentInfoServiceImpl extends BaseServiceImpl<CommentMapper, CommentInfo> implements CommentInfoService {

    private final UserInfoService userInfoService;

    @Override
    public R<String> createComment(CommentInfo commentInfo) {
        if (this.save(commentInfo)) {
            return R.ok("评论成功");
        }
        return R.error("评论失败");
    }

    @Override
    public R<String> deleteComment(Long id) {
        if (this.removeById(id)) {
            return R.ok("删除成功");
        }
        return R.error("删除失败");
    }

    @Override
    public List<CommentInfo> getComment(Long postsId) {
        LambdaQueryWrapper<CommentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommentInfo::getPostsId, postsId);
        List<CommentInfo> commentInfos = this.list(wrapper);

        List<UserInfo> lists = userInfoService.list();
        Map<Long, String> userMap = lists.stream().collect(Collectors.toMap(UserInfo::getId, UserInfo::getName));

        for (CommentInfo commentInfo : commentInfos) {
            commentInfo.setUserName(userMap.getOrDefault(commentInfo.getUserId(), ""));
        }
        return commentInfos;
    }


    @Override
    public Map<Long, Long> getCount() {
        List<CommentInfo> lists = this.list();
        return lists.stream().collect(Collectors.groupingBy(CommentInfo::getPostsId, Collectors.counting()));
    }
}
